/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.*;
import com.je.bpm.engine.runtime.Execution;

import java.util.Collection;
import java.util.List;

public abstract class AbstractSetProcessInstanceStateCmd implements Command<Void> {

    protected final String processInstanceId;

    public AbstractSetProcessInstanceStateCmd(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    @Override
    public Void execute(CommandContext commandContext) {

        if (processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("ProcessInstanceId cannot be null.");
        }

        ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findById(processInstanceId);

        if (executionEntity == null) {
            throw new ActivitiObjectNotFoundException("Cannot find processInstance for id '" + processInstanceId + "'.", Execution.class);
        }
        if (!executionEntity.isProcessInstanceType()) {
            throw new ActivitiException("Cannot set suspension state for execution '" + processInstanceId + "': not a process instance.");
        }

        SuspensionState.SuspensionStateUtil.setSuspensionState(executionEntity, getNewState());
        commandContext.getExecutionEntityManager().update(executionEntity, false);

        // All child executions are suspended
        Collection<ExecutionEntity> childExecutions = commandContext.getExecutionEntityManager().findChildExecutionsByProcessInstanceId(processInstanceId);
        for (ExecutionEntity childExecution : childExecutions) {
            if (!childExecution.getId().equals(processInstanceId)) {
                SuspensionState.SuspensionStateUtil.setSuspensionState(childExecution, getNewState());
                commandContext.getExecutionEntityManager().update(childExecution, false);
            }
        }

        // All tasks are suspended
        List<TaskEntity> tasks = commandContext.getTaskEntityManager().findTasksByProcessInstanceId(processInstanceId);
        for (TaskEntity taskEntity : tasks) {
            SuspensionState.SuspensionStateUtil.setSuspensionState(taskEntity, getNewState());
            commandContext.getTaskEntityManager().update(taskEntity, false);
        }

        // All jobs are suspended
        if (getNewState() == SuspensionState.ACTIVE) {
            List<SuspendedJobEntity> suspendedJobs = commandContext.getSuspendedJobEntityManager().findJobsByProcessInstanceId(processInstanceId);
            for (SuspendedJobEntity suspendedJob : suspendedJobs) {
                commandContext.getJobManager().activateSuspendedJob(suspendedJob);
            }
        } else {
            List<TimerJobEntity> timerJobs = commandContext.getTimerJobEntityManager().findJobsByProcessInstanceId(processInstanceId);
            for (TimerJobEntity timerJob : timerJobs) {
                commandContext.getJobManager().moveJobToSuspendedJob(timerJob);
            }
            List<JobEntity> jobs = commandContext.getJobEntityManager().findJobsByProcessInstanceId(processInstanceId);
            for (JobEntity job : jobs) {
                commandContext.getJobManager().moveJobToSuspendedJob(job);
            }
        }

        return null;
    }

    protected abstract SuspensionState getNewState();

}
